package com.example.controller;

import com.example.chat.UDPClient;
import com.example.pojo.ChangePassword;
import com.example.pojo.Result;
import com.example.pojo.Student;
import com.example.service.LoginService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @PostMapping("/login")
    public Result login(@RequestBody Student student){
        log.info("登录功能：{},{}",student.getStudentID(),student.getPassword());
        student = loginService.login(student);

        if (student != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",student.getId());
            claims.put("name",student.getName());
            claims.put("studentID",student.getStudentID());
            String jwt = JwtUtils.generateJwt(claims);                                      //jwt中包含了学生的信息
            try {
                /**
                  *聊天室
                 这个东西，我不是很会写，随便想的写的，我网上跟的课也没有，纯虚造，很浪费资源
                 登录之后会开启一个线程，
                 */
                new UDPClient().ConnectTOServerForTCP(jwt);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("登录成功！");
            return Result.success(jwt);
        }
        log.warn("登录失败！");
        return Result.error("用户名或密码错误！");
    }

    @PutMapping("/changePassword")
    public Result changePassword(@RequestBody  ChangePassword changePassword){
        log.info("修改密码   --->>>   传入的参数：{}",changePassword);
        Result result =  loginService.changePassword(changePassword);
        log.info("修改密码成功！");
        return result;
    }

    @PostMapping("/registryStudentID")
    public Result registryStudentID(@RequestBody  Student student){
        log.info("注册用户：  --->>> 学号：{}，新密码：{}",student.getStudentID(),student.getPassword());
        Result result = loginService.registryStudentID(student);
        log.info("注册成功！");
        return result;
    }

}
